package ysq.xyg.recovery.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import ysq.xyg.base.model.dto.ReturnEntity;
import ysq.xyg.base.service.impl.BaseServiceImpl;
import ysq.xyg.base.util.BaseConstant;
import ysq.xyg.base.util.BaseUtil;
import ysq.xyg.recovery.dao.RecoverySackRecordDao;
import ysq.xyg.recovery.model.po.*;
import ysq.xyg.recovery.model.vo.RecoveryRecordVo;
import ysq.xyg.recovery.model.vo.RecoverySackDetailVo;
import ysq.xyg.recovery.model.vo.RecoverySackRecordVo;
import ysq.xyg.recovery.model.vo.RecoverySackVo;
import ysq.xyg.recovery.service.*;
import ysq.xyg.sys.model.po.SysUser;
import ysq.xyg.web.model.po.WebMember;
import ysq.xyg.web.service.WebMemberService;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 回收金模块-袋子记录表service实现
 *
 * @author congcong tao
 * @date 2019-7-8 14:46:54
 */
@Service("recoverySackRecordService")
public class RecoverySackRecordServiceImpl extends BaseServiceImpl<RecoverySackRecord> implements RecoverySackRecordService {

    @Autowired
    private WebMemberService webMemberService;
    @Autowired
    private RecoverySackService recoverySackService;
    @Autowired
    private RecoverySackMemberService recoverySackMemberService;
    @Autowired
    private RecoverySackDetailService recoverySackDetailService;
    @Autowired
    private RecoveryOrderService recoveryOrderService;
    @Autowired
    private RecoveryRecordService recoveryRecordService;

    @Resource
    private RecoverySackRecordDao recoverySackRecordDao;
    @Autowired
    public void setBaseDao(RecoverySackRecordDao recoverySackRecordDao) {
        this.baseDao = recoverySackRecordDao;
    }

    private RecoverySackRecord recoverySackRecord;

    /**
     * 分页查询
     *
     * @param recoverySackRecordVo 对象
     * @param pageSize 展示数量
     * @param pageNum 当前页面
     * @return ReturnEntity 对象
     * @author congcong tao
     * @date 2019-7-8 14:46:54
     */
    @Override
    public ReturnEntity page(RecoverySackRecordVo recoverySackRecordVo, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        PageHelper.orderBy(" update_time desc");
        List<RecoverySackRecord> list = acceptList(recoverySackRecordVo);
        PageInfo<RecoverySackRecord> page=new PageInfo<RecoverySackRecord>(list);
        return new ReturnEntity(page.getList(),page.getTotal(),page.isHasNextPage());
    }

    @Override
    public ReturnEntity pageLeft(RecoverySackRecordVo recoverySackRecordVo, int pageSize, int pageNum) {
        if (StringUtils.isNotEmpty(recoverySackRecordVo.getMemberNickName())) {
            recoverySackRecordVo.setMemberNickName(BaseUtil.encodeBase64String(recoverySackRecordVo.getMemberNickName()));
        }
        PageHelper.startPage(pageNum,pageSize);
        // PageHelper.orderBy(" update_time desc");
        List<RecoverySackRecord> list = recoverySackRecordDao.selectEntityList(recoverySackRecordVo);
        if (list != null && list.size() > 0) {
            for (RecoverySackRecord sackRecord : list) {
                if (StringUtils.isNotEmpty(sackRecord.getMemberNickName())) {
                    sackRecord.setMemberNickName(BaseUtil.decodeBase64(sackRecord.getMemberNickName()));
                }
                if (StringUtils.isNotEmpty(sackRecord.getMemberCoverNickName())) {
                    sackRecord.setMemberCoverNickName(BaseUtil.decodeBase64(sackRecord.getMemberCoverNickName()));
                }
            }
        }
        PageInfo<RecoverySackRecord> page=new PageInfo<RecoverySackRecord>(list);
        return new ReturnEntity(page.getList(),page.getTotal(),page.isHasNextPage());
    }

    /**
     * 修改
     *
     * @param recoverySackRecordVo 对象
     * @param currentUser 当前用户
     * @return ReturnEntity 对象
     * @author congcong tao
     * @date 2019-7-8 14:46:54
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public ReturnEntity addOrUpdate(RecoverySackRecordVo recoverySackRecordVo, SysUser currentUser) {
        boolean isUpate=true;
        if(StrUtil.isEmpty(recoverySackRecordVo.getId())){
            recoverySackRecord=new RecoverySackRecord(currentUser);
            isUpate=false;
        }else{
            recoverySackRecord=selectByPrimaryKey(recoverySackRecordVo.getId());
            if(ObjectUtil.isNull(recoverySackRecord)){
                return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
            }
            recoverySackRecord.setUpdateTime(new Date());
            recoverySackRecord.setUpdateUser(currentUser.getId());
        }
        recoverySackRecord.setSackMemberId(recoverySackRecordVo.getSackMemberId());
        recoverySackRecord.setStackNum(recoverySackRecordVo.getStackNum());
        recoverySackRecord.setMemberId(recoverySackRecordVo.getMemberId());
        recoverySackRecord.setMemberAddress(recoverySackRecordVo.getMemberAddress());
        recoverySackRecord.setMemberPhone(recoverySackRecordVo.getMemberPhone());
        recoverySackRecord.setMemberCoverId(recoverySackRecordVo.getMemberCoverId());
        recoverySackRecord.setMemberCoverPhone(recoverySackRecordVo.getMemberCoverPhone());
        recoverySackRecord.setNumber(recoverySackRecordVo.getNumber());
        recoverySackRecord.setQrImage(recoverySackRecordVo.getQrImage());
        recoverySackRecord.setContent(recoverySackRecordVo.getContent());
        recoverySackRecord.setStatus(recoverySackRecordVo.getStatus());
        int num = 0;
        if (isUpate) {
            num = updateByPrimaryKey(recoverySackRecord);
        } else {
            num = insert(recoverySackRecord);
        }
        if (num <= 0) {
            return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
        }
        // 加入member信息
        if (StringUtils.isNotEmpty(recoverySackRecordVo.getMemberId())) {
            WebMember webMember = webMemberService.selectByPrimaryKey(recoverySackRecordVo.getMemberId());
            if (webMember != null) {
                recoverySackRecord.setMemberCardNo(webMember.getCardNo());
                recoverySackRecord.setMemberName(webMember.getName());
            }
        }
        return new ReturnEntity(recoverySackRecord);
    }

    /**
     * 删除
     *
     * @param id 主键id
     * @param currentUser 当前用户
     * @return ReturnEntity 对象
     * @author congcong tao
     * @date 2019-7-8 14:46:54
     */
    @Override
    public ReturnEntity delete(String id, SysUser currentUser) {
        RecoverySackRecord recoverySackRecord=selectByPrimaryKey(id);
        if(recoverySackRecord!=null){
            recoverySackRecord.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_DELETE);
            recoverySackRecord.setUpdateTime(new Date());
            recoverySackRecord.setUpdateUser(currentUser.getId());
            int num=updateByPrimaryKey(recoverySackRecord);
            if(num>0){
                return new ReturnEntity();
            }
        }
        return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
    }

    /**
     * 获取集合
     *
     * @param recoverySackRecordVo 对象
     * @return List<BaseDict> BaseDict集合
     * @author congcong tao
     * @date 2019-7-8 14:46:54
     */
    @Override
    public List<RecoverySackRecord> acceptList(RecoverySackRecordVo recoverySackRecordVo){
        Example example = new Example(RecoverySackRecord.class);
        Example.Criteria criteria = example.createCriteria();
        if(StringUtil.isNotEmpty(recoverySackRecordVo.getRemoveTag())){
            criteria.andEqualTo("removeTag",recoverySackRecordVo.getRemoveTag());
        }
        example.setOrderByClause(" update_time desc");
        return recoverySackRecordDao.selectByExample(example);
    }

    @Override
    public ReturnEntity updateSackRecord(RecoverySackRecordVo recoverySackRecordVo) {
        String memberCoverId = recoverySackRecordVo.getMemberCoverId();
        // 预约会生成记录，现有id
        WebMember memberCover = webMemberService.selectByPrimaryKey(memberCoverId);
        RecoverySackRecord recoveryRecord = this.selectByPrimaryKey(recoverySackRecordVo.getId());
        recoveryRecord.setMemberCoverId(memberCoverId);
        if (memberCover != null && StringUtils.isNotEmpty(memberCover.getPhone())) {
            recoveryRecord.setMemberCoverPhone(memberCover.getPhone());
        }
        recoveryRecord.setUpdateTime(DateUtil.date());
        recoveryRecord.setManageTime(DateUtil.date());
        recoveryRecord.setStatus(BaseConstant.RECOVERY_RECORD_STATUS_TWO);
        // recoveryRecord.setMemberAddress(recoverySackRecordVo.getMemberAddress());
        // recoveryRecord.setMemberPhone(recoverySackRecordVo.getMemberPhone());
        int info = this.updateByPrimaryKeySelective(recoveryRecord);
        if (info <= 0) {
            return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
        }
        // 查看是否购买，如果购买才能绑定
        // 查询是否已存在订单
        RecoveryOrder orderSearch = new RecoveryOrder();
        orderSearch.setMemberId(recoveryRecord.getMemberId());
        List<RecoveryOrder> recoveryOrderList = recoveryOrderService.select(orderSearch);
        if (recoveryOrderList == null || recoveryOrderList.size() == 0) {
            return new ReturnEntity(BaseConstant.SUCCESS, "绑定新袋子未查询到购买记录");
        }
        int num = 0;
        for (RecoveryOrder recoveryOrder : recoveryOrderList) {
            num = num + recoveryOrder.getNum();
        }
        // 正在使用的袋子,正在使用的
        RecoverySackMember recoverySackMemberVo = new RecoverySackMember();
        recoverySackMemberVo.setMemberId(recoveryRecord.getMemberId());
        recoverySackMemberVo.setStatus(BaseConstant.RECOVERY_SACK_MEMBER_STATUS_USEING);
        int memberNum = recoverySackMemberService.selectCount(recoverySackMemberVo);
        if (memberNum > num) {
            return new ReturnEntity(BaseConstant.SUCCESS, "绑定新袋子未查询购买记录");
        }
        // 需要绑定袋子。即重新生成数据
        String newStackNum = recoverySackRecordVo.getNewStackNum();
        if (StringUtils.isNotEmpty(newStackNum)) {
            RecoverySackVo recoverySackVo = new RecoverySackVo();
            recoverySackVo.setCardNo(newStackNum);
            recoverySackVo.setStatus(BaseConstant.RECOVERY_SACK_STATUS_UNUSED);
            recoverySackVo.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_NORMAL);
            List<RecoverySack> recoverySackList = recoverySackService.acceptList(recoverySackVo);
            if (recoverySackList != null && recoverySackList.size() > 0) {
                RecoverySack recoverySack = recoverySackList.get(0);
                // 绑定至member
                RecoverySackMember recoverySackMember = new RecoverySackMember();
                recoverySackMember.setId(BaseUtil.uId());
                recoverySackMember.setMemberId(recoveryRecord.getMemberId());
                recoverySackMember.setSackId(recoverySack.getId());
                recoverySackMember.setStatus(BaseConstant.RECOVERY_SACK_MEMBER_STATUS_USEING);
                recoverySackMember.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_NORMAL);
                recoverySackMember.setCreateTime(DateUtil.date());
                recoverySackMember.setUpdateTime(DateUtil.date());
                recoverySackMemberService.insert(recoverySackMember);
                // 并将新的sack表状态修改为已使用
                recoverySack.setStatus(BaseConstant.RECOVERY_SACK_STATUS_USED);
                recoverySackService.updateByPrimaryKeySelective(recoverySack);
            }
        }
        return new ReturnEntity();
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public ReturnEntity completeSack(String id) {
        // 完成盘点
        RecoverySackRecord sackRecord = this.selectByPrimaryKey(id);
        String sackMemberId = sackRecord.getSackMemberId();
        RecoverySackMember recoverySackMember = recoverySackMemberService.selectByPrimaryKey(sackMemberId);
        String sackId = recoverySackMember.getSackId();
        RecoverySack recoverySack = recoverySackService.selectByPrimaryKey(sackId);
        // 盘点的详情数据
        RecoverySackDetailVo recoverySackDetailVo = new RecoverySackDetailVo();
        recoverySackDetailVo.setRecordId(sackRecord.getId());
        recoverySackDetailVo.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_NORMAL);
        List<RecoverySackDetail> sackDetailList = recoverySackDetailService.acceptList(recoverySackDetailVo);
        Double allPrice = 0.0d;
        if (sackDetailList != null && sackDetailList.size() > 0) {
            for (RecoverySackDetail sackDetail : sackDetailList) {
                if (StringUtils.isNotEmpty(sackDetail.getAllPrice())) {
                    allPrice = allPrice + Double.parseDouble(sackDetail.getAllPrice());
                }
            }
        }

        // 盘点完成
        sackRecord.setStatus(BaseConstant.RECOVERY_RECORD_STATUS_THREE);
        // 使用结束
        recoverySackMember.setStatus(BaseConstant.RECOVERY_SACK_MEMBER_STATUS_USED);
        // 将袋子释放，袋子属于未使用
        recoverySack.setStatus(BaseConstant.RECOVERY_SACK_STATUS_UNUSED);

        this.updateByPrimaryKeySelective(sackRecord);
        recoverySackMemberService.updateByPrimaryKeySelective(recoverySackMember);
        recoverySackService.updateByPrimaryKeySelective(recoverySack);

        // 需要计算总金额，并提交到webMember中
        WebMember webMember = webMemberService.selectByPrimaryKey(sackRecord.getMemberId());
        webMember.setMoney(webMember.getMoney() + allPrice);
        // 1:1计算积分,可能会损失精度
        int score = (int)(allPrice * 10);
        webMember.setScore(webMember.getScore() + score);
        webMemberService.updateByPrimaryKeySelective(webMember);

        // 积分记录表
        RecoveryRecord recoveryRecord = new RecoveryRecord();
        recoveryRecord.setId(BaseUtil.uId());
        recoveryRecord.setMemberId(sackRecord.getMemberId());
        recoveryRecord.setMoney(String.valueOf(score));
        recoveryRecord.setDescription(String.format("回收物品增加%s积分", score));
        recoveryRecord.setCreateTime(DateUtil.date());
        recoveryRecord.setUpdateTime(recoveryRecord.getCreateTime());
        recoveryRecord.setType(BaseConstant.RECORD_STATUS_ADD_SCORE);
        recoveryRecord.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_NORMAL);
        recoveryRecordService.insert(recoveryRecord);

        // 金额记录表
        /*RecoveryRecord recoveryRecordM = new RecoveryRecord();
        recoveryRecordM.setId(BaseUtil.uId());
        recoveryRecordM.setMemberId(sackRecord.getMemberId());
        recoveryRecordM.setMoney(String.valueOf(allPrice));
        recoveryRecordM.setCreateTime(DateUtil.date());
        recoveryRecordM.setUpdateTime(recoveryRecord.getCreateTime());
        recoveryRecordM.setType(BaseConstant.RECOVERY_TYPE_PERMISSION);
        recoveryRecord.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_NORMAL);
        recoveryRecordService.insert(recoveryRecord);*/
        return new ReturnEntity();
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public ReturnEntity completeOrder(String id) {
        // 完成盘点
        RecoverySackRecord sackRecord = this.selectByPrimaryKey(id);
        sackRecord.setStatus(BaseConstant.RECOVERY_RECORD_STATUS_THREE);
        this.updateByPrimaryKey(sackRecord);
        // 盘点的详情数据
        RecoverySackDetailVo recoverySackDetailVo = new RecoverySackDetailVo();
        recoverySackDetailVo.setRecordId(sackRecord.getId());
        recoverySackDetailVo.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_NORMAL);
        List<RecoverySackDetail> sackDetailList = recoverySackDetailService.acceptList(recoverySackDetailVo);
        Double allPrice = 0.0d;
        if (sackDetailList != null && sackDetailList.size() > 0) {
            for (RecoverySackDetail sackDetail : sackDetailList) {
                if (StringUtils.isNotEmpty(sackDetail.getAllPrice())) {
                    allPrice = allPrice + Double.parseDouble(sackDetail.getAllPrice());
                }
            }
        }
        // 加金额
        RecoveryRecordVo recoveryRecordVo = new RecoveryRecordVo();
        recoveryRecordVo.setMemberId(sackRecord.getMemberId());
        recoveryRecordVo.setType(BaseConstant.RECOVERY_TYPE_PERMISSION);
        recoveryRecordVo.setMoney(String.valueOf(allPrice));
        // 加积分
        // 1:1计算积分,可能会损失精度
        WebMember webMember = webMemberService.selectByPrimaryKey(sackRecord.getMemberId());
        // 1:1计算积分,可能会损失精度
        int score = (int)(allPrice * 10);
        webMember.setScore(webMember.getScore() + score);
        webMemberService.updateByPrimaryKeySelective(webMember);
        // 积分记录表
        RecoveryRecord recoveryRecord = new RecoveryRecord();
        recoveryRecord.setId(BaseUtil.uId());
        recoveryRecord.setMemberId(sackRecord.getMemberId());
        recoveryRecord.setMoney(String.valueOf(score));
        recoveryRecord.setDescription(String.format("回收物品增加%s积分", score));
        recoveryRecord.setCreateTime(DateUtil.date());
        recoveryRecord.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_NORMAL);
        recoveryRecord.setUpdateTime(recoveryRecord.getCreateTime());
        recoveryRecord.setType(BaseConstant.RECORD_STATUS_ADD_SCORE);
        recoveryRecordService.insert(recoveryRecord);

        return recoveryRecordService.saveRecoveryRecord(recoveryRecordVo);
    }
}
